<template>
  <div class="wangeditor-container">
    <Toolbar
      style="border-bottom: 1px solid #d1d5db"
      :editor="editorRef"
      :default-config="toolbarConfig"
      mode="default"
    />
    <Editor
      v-model="model"
      style="min-height: 301px"
      :default-config="editorConfig"
      mode="default"
      @on-created="handleCreated"
      @on-change="handleChange"
      @custom-pste="customPaste"
    />
  </div>
</template>

<script setup lang="ts">
import "@wangeditor-next/editor/dist/css/style.css";

import { onBeforeUnmount, ref, shallowRef } from "vue";
import { DomEditor } from "@wangeditor-next/editor";
import { Editor, Toolbar } from "@wangeditor-next/editor-for-vue";

import type { IToolbarConfig, IEditorConfig, IDomEditor } from "@wangeditor-next/editor";
import { fileApi } from "@/api/file";

const props = defineProps({
  /* 语言 */
  lang: { type: String, default: "zh-cn" },
  /* 工具栏配置 */
  toolbar: {
    type: Object as PropType<Partial<IToolbarConfig>>,
    default: () => {}
  }
});

// 工具栏配置
const toolbarConfig: Partial<IToolbarConfig> = {
  ...props.toolbar
};

const editorConfig = ref<Partial<IEditorConfig>>({
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      customUpload(file: File, insertFn: InsertFnType) {
        fileApi.uploadApi(file).then((res) => {
          // 插入图片
           insertFn(fileApi.fileCompleteUrl(res.data.fileSrc as string));
        });
      }, 
    } as any,
    uploadVideo :{
       customUpload(file: File, insertFn: InsertFnType) {
        fileApi.uploadApi(file).then((res) => {
          // 插入图片
           insertFn(fileApi.fileCompleteUrl(res.data.fileSrc as string));
        });
      }, 
    }as any
  },
  autoFocus: false
});
type InsertFnType = (url: string, alt?: string, href?: string) => void;


const editorRef = shallowRef();
const model = defineModel<string>();
// 富文本编辑器生成后触发
function handleCreated(editor: IDomEditor) {
  editorRef.value = editor;
}

const toolbarMenuConfig = ref();

// 监听富文本编辑器内容变化
function handleChange(editor: IDomEditor) {
  toolbarMenuConfig.value = DomEditor.getToolbar(editor);
}

// 监听富文本编辑器粘贴行为
function customPaste(editor: IDomEditor, event: ClipboardEvent, callback: any) {
  // 获取粘贴的纯文本
  if (event.clipboardData) {
    const text = event.clipboardData.getData("text/plain");
    if (text) {
      editor.insertText(text);
      event.preventDefault();
      callback(false);
    }
  }
}

defineExpose({ toolbarMenuConfig: () => toolbarMenuConfig.value });

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<style lang="scss" scoped>
.wangeditor-container {
  border: 1px solid #d1d5db;
  width: 100%;
  box-sizing: border-box;
  z-index: 100000;
}

:deep(.w-e-full-screen-container) {
  z-index: 100000;
}

:deep(.w-e-scroll),
:deep(#w-e-textarea-1),
:deep(.w-e-text-container) {
  min-height: 301px;
}
</style>
